package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.MeiTuanConfig;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.BannerPictureMapper;
import com.eco.fanliapp.dao.SyModuleChildrenMapper;
import com.eco.fanliapp.dao.SyModuleMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.jd.JDConfig;
import com.eco.fanliapp.pinduoduo.PDDConfig;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.taobao.SessionController;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.utils.HttpUtils;
import com.eco.fanliapp.utils.MeiTuanAEC;
import com.eco.fanliapp.utils.SignMD5Util;
import com.eco.fanliapp.vo.*;
import com.eco.fanliapp.vo.respone.PDDUrlResponse;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.taobao.api.response.TbkScActivitylinkToolgetResponse;
import jd.union.open.promotion.bysubunionid.get.request.PromotionCodeReq;
import jd.union.open.promotion.bysubunionid.get.request.UnionOpenPromotionBysubunionidGetRequest;
import jd.union.open.promotion.bysubunionid.get.response.UnionOpenPromotionBysubunionidGetResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 模块表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-09-09
 */
@Service
public class SyModuleServiceImpl extends ServiceImpl<SyModuleMapper, SyModule> implements ISyModuleService {
    @Autowired
    private SyModuleMapper syModuleMapper;
    @Autowired
    private SyModuleChildrenMapper syModuleChildrenMapper;
    @Autowired
    private BannerPictureMapper bannerPictureMapper;
    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private IAppUserRewardSetupService iAppUserRewardSetupService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private ISyUserTaskService iSyUserTaskService;
    @Autowired
    private IAppUserRedRewardService iAppUserRedRewardService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private ITaobaoSchemeService iTaobaoSchemeService;
    @Autowired
    private SessionController sessionController;
    @Autowired
    private IAppCompanyService appCompanyService;

    @Override
    public ServerResponse moduleListCompany(Integer companyId) {
        String redisModuleKey = "module_list_company====";
        HashMap map = new HashMap();
        if (redisTemplateService.hasKey(redisModuleKey)) {
            map = redisTemplateService.getMap(redisModuleKey, HashMap.class);
        }
        if (map.size() <= 0) {
            List<BannerPictureVo> bannerAdvertisingList = new ArrayList<>();
            List<BannerPictureVo> freeList = new ArrayList<>();
            List<BannerPictureVo> taoBaoActivityList = new ArrayList<>();
            //排序
            List<SyModuleVo> syModuleList = syModuleMapper.syModuleList();
            for (SyModuleVo syModuleVo : syModuleList) {
                if (syModuleVo.getTableId() == 3) {
                    //广告位
                    bannerAdvertisingList = bannerPictureMapper.bannerModuleList(1, companyId);
                } else if (syModuleVo.getTableId() == 4) {
                    //免单模块
                    freeList = bannerPictureMapper.bannerModuleList(2, null);
                } else if (syModuleVo.getTableId() == 5) {
                    //淘宝活动
                    taoBaoActivityList = bannerPictureMapper.bannerModuleList(3, null);
                }
            }
            map.put("bannerAdvertising", bannerAdvertisingList);
            map.put("freeModule", freeList);
            map.put("TaoBaoActivity", taoBaoActivityList);
            redisTemplateService.addMap(redisModuleKey, map);
        }
        return ServerResponse.createBySuccess("查询成功", map);
    }

    /**
     * 三步省钱
     *
     * @return
     */
    @Override
    public ServerResponse moneyTutorial() {
        String redisKeyStr = "app_step_save_money";
        List<MoneyTutorialVo> moneyTutorialList = null;
        if (redisTemplateService.hasKey(redisKeyStr)) {
            moneyTutorialList = redisTemplateService.getTByListKey(redisKeyStr, MoneyTutorialVo.class);
        }
        if (moneyTutorialList == null) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("enable", 1);
            queryWrapper.eq("deleted", 0);
            queryWrapper.eq("module_name", "三步省钱");
            List<SyModule> syModuleList = syModuleMapper.selectList(queryWrapper);

            if (syModuleList != null && syModuleList.size() == 1) {
                moneyTutorialList = syModuleChildrenMapper.moneyTutorial(syModuleList.get(0).getTableId());
            }
            if (moneyTutorialList != null) {
                redisTemplateService.set(redisKeyStr, moneyTutorialList, 60 * 5);
            }

        }
        if (moneyTutorialList.size() > 0) {
            return ServerResponse.createBySuccess("查询成功", moneyTutorialList);
        }

        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
    }

    /**
     * 今日爆款
     *
     * @param star
     * @param end
     * @param cid
     * @return
     */
    @Override
    public ServerResponse kingKongSonList(Integer star, Integer end, Integer cid, Integer kType) {
        List<AppGoodsVo> list = null;
        if (redisTemplate.hasKey("kingKongSonList" + star + end + cid + kType)) {
            list = (List<AppGoodsVo>) redisTemplate.opsForValue().get("kingKongSonList" + star + end + cid + kType);
        } else {
            list = iAppGoodsService.kingKongSonList(star, end, cid, kType);
            redisTemplate.opsForValue().set("kingKongSonList" + star + end + cid + kType, list, 5, TimeUnit.MINUTES);
        }
        Map map = new HashMap<>();
        if (list != null && list.size() > 0) {
            map.put("min_id", null);
            map.put("data", list);
            return ServerResponse.createBySuccess("查询成功", map);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
        }
    }

    /**
     * 首页海报模块
     *
     * @return
     */
    @Override
    public ServerResponse homePosterModule() {
        String redisKeyStr = "app_advertising_h5_onOff";
        HashMap map = new HashMap();
        if (redisTemplateService.hasKey(redisKeyStr)) {
            map = redisTemplateService.getTByKey(redisKeyStr, HashMap.class);
        }
        if (map.size() == 0) {
            SyModule syModule = getById(8);
            if (syModule.getEnable()) {
                List<BannerPictureVo> bannerPopupList = bannerPictureMapper.bannerModuleList(5, null);//首页海报5
                if (bannerPopupList.size() > 0) {
                    String key = "sy_banner_poster_height";
                    if (redisTemplate.hasKey(key)) {
                        map.put("high", redisTemplate.opsForValue().get(key));
                    } else {
                        map.put("high", "35");
                    }
                    map.put("onOff", true);

                    redisTemplateService.set(redisKeyStr, map, 60 * 5);
                } else {
                    return ServerResponse.createBySuccess(201, "暂无数据", map);
                }
            }
        }
        return ServerResponse.createBySuccess("查询成功", map);
    }

    /**
     * 红包列表/金刚区
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse moduleReveal(Long userId) {
        //金刚眼模块 红包列表互斥
        HashMap map = new HashMap();
        //7天时间戳
        long time = 604800000L;
        //红包对照表
        AppUserRewardSetup appUserRewardSetup = null;

        if (redisTemplateService.hasKey("AppUserRewardSetup")) {
            appUserRewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup", AppUserRewardSetup.class);
        } else {
            appUserRewardSetup = iAppUserRewardSetupService.getById(1);
            redisTemplateService.set("AppUserRewardSetup", appUserRewardSetup, 60 * 60);
        }

        if (userId != null) {
            //美团链接放入缓存
            String meiTuanKey = "meiTuanUrl_" + userId;
            //京东链接放入缓存
            String JDKey = "JDUrl_" + userId;
            String PDDKey = "PDDUrl_" + userId;
            String ELMKey = "ELMUrl_" + userId;
            String mt_url = "";
            String jd_url = "";
            String pdd_url = "";
            String elm_url = "";
            //查询金刚眼模块
            SyModuleVo kkeSyModule = null;
            //查询金刚眼子模块
            List<SyModuleChildrenVo> kingKongChildrenList = null;

            if (redisTemplateService.hasKey("app_module_kingkong")) {
                kkeSyModule = redisTemplateService.getTByKey("app_module_kingkong", SyModuleVo.class);
            } else {
                //查询金刚眼模块
                kkeSyModule = syModuleMapper.kingKong();
                redisTemplateService.set("app_module_kingkong", kkeSyModule, 60 * 60);
            }
            //查询金刚眼子模块
            if (redisTemplateService.hasKey("app_module_kingkong_list")) {
                kingKongChildrenList = redisTemplateService.getTByListKey("app_module_kingkong_list", SyModuleChildrenVo.class);
            } else {
                //查询金刚眼模块
                kingKongChildrenList = syModuleChildrenMapper.kingKongChildrenList();
                redisTemplateService.set("app_module_kingkong_list", kingKongChildrenList, 60 * 5);
            }

            if (kingKongChildrenList == null || kingKongChildrenList.size() <= 0) {
                return ServerResponse.createBySuccess(201, "暂无数据", null);
            }
            for (SyModuleChildrenVo syModuleChildrenVo : kingKongChildrenList
            ) {

                if ("11".equals(syModuleChildrenVo.getJumpType())) {
                    //美团链接code = 5
                    if(syModuleChildrenVo.getModuleCode() == 5){
                        if (redisTemplateService.hasKey(meiTuanKey)) {
                            mt_url = redisTemplateService.getTByKey(meiTuanKey, String.class);
                        } else {
                            mt_url = getMeiTuanUrl(userId);
                            redisTemplateService.set(meiTuanKey, mt_url, 60 * 60 * 24 * 7);
                        }
                        syModuleChildrenVo.setModuleLink(mt_url);
                        continue;
                    }
                    //京东链接code = 6
                    if (syModuleChildrenVo.getModuleCode() == 6) {
                        if (redisTemplateService.hasKey(JDKey)) {
                            jd_url = redisTemplateService.getTByKey(JDKey, String.class);
                        }
                        if ("".equals(jd_url)) {
                            jd_url = getJingDongUrl(userId, JDConfig.JD_MATERIAL_ID, null);
                            redisTemplateService.set(JDKey, jd_url, 60 * 60 * 24 * 7);
                        }
                        syModuleChildrenVo.setModuleLink(jd_url);
                        continue;
                    }
                    //拼多多链接 code = 7
                    if (syModuleChildrenVo.getModuleCode() == 7) {
                        if (redisTemplateService.hasKey(PDDKey)) {
                            pdd_url = redisTemplateService.getTByKey(PDDKey, String.class);
                        }
                        if ("".equals(pdd_url)) {
                            pdd_url = getPinDuoDuoUrl(userId);
                            redisTemplateService.set(PDDKey, pdd_url, 60 * 60 * 24 * 7);
                        }
                        syModuleChildrenVo.setModuleLink(pdd_url);
                        continue;
                    }
                    if(syModuleChildrenVo.getModuleCode() == 8){
                        //饿了吗活动转链code = 8
                        if (redisTemplateService.hasKey(ELMKey)) {
                            elm_url = redisTemplateService.getTByKey(ELMKey, String.class);
                        }
                        if ("".equals(elm_url)) {
                            elm_url = getElmUrl(userId);
                            redisTemplateService.set(ELMKey, elm_url, 60 * 60 * 24);
                        }
                        syModuleChildrenVo.setModuleLink(elm_url);
                        continue;
                    }
                }
            }
            //用户登录，未完成任务展示七天红列表，完成任务（3）隐藏红包列表展示金刚眼
            //1 根据userId查询用户
            AppUser appUser = iAppUserService.selectAppUserByUserId(userId, 1);

            //判断用户是否完成任务
            Integer taskNum = iSyUserTaskService.taskFinishNumber(userId);
            //是否购买免单
            ServerResponse response = iGoodsFreeService.checkHaveBuy(userId, null);

            long loseTime = 0L;
            //以首次登陆时间为依据，判断时间是否超过7天
            Date loginDate = null;
            long loginTime = 0L;
            if (appUser == null) {
                return ServerResponse.createBySuccess(301, "请重新登录", null);
            } else if (appUser.getUserLoginTime() == null) {
                //没有首次登陆时间，默认为老用户，老用户展示金刚区，不展示红包列表
                //隐藏免单
                for (SyModuleChildrenVo syModuleChildrenVo : kingKongChildrenList) {
                    if ("3".equals(syModuleChildrenVo.getJumpType())) {
                        kingKongChildrenList.remove(syModuleChildrenVo);
                        break;
                    }
                }
                if (kkeSyModule != null && kingKongChildrenList != null && kingKongChildrenList.size() > 0) {
                    kkeSyModule.setModuleChildrenList(kingKongChildrenList);
                    map.put("moduleType", "a");//金刚眼返回a
                    map.put("kingKongEye", kkeSyModule);
                    return ServerResponse.createBySuccess("查询成功", map);
                } else {
                    return ServerResponse.createBySuccess(201, "暂无数据", null);
                }

            } else if (appUser.getUserLoginTime() != null) {

                //以首次登陆时间为依据，判断时间是否超过7天
                loginDate = appUser.getUserLoginTime();
                Date loginDate2 = DateUtils.updateDayByDate(loginDate, 7);

                loginTime = loginDate2.getTime();

                loseTime = loginTime - System.currentTimeMillis();
                if (loseTime <= 0) {
                    //隐藏免单
                    for (SyModuleChildrenVo syModuleChildrenVo : kingKongChildrenList) {
                        if ("3".equals(syModuleChildrenVo.getJumpType())) {
                            kingKongChildrenList.remove(syModuleChildrenVo);
                            break;
                        }
                    }
                    if (kkeSyModule != null && kingKongChildrenList != null && kingKongChildrenList.size() > 0) {
                        kkeSyModule.setModuleChildrenList(kingKongChildrenList);
                        map.put("moduleType", "a");//金刚眼返回a
                        map.put("kingKongEye", kkeSyModule);
                        return ServerResponse.createBySuccess("查询成功", map);
                    } else {
                        return ServerResponse.createBySuccess(201, "暂无数据", null);
                    }
                } else {
                    //复制链接任务，首购任务，订单状态，0未完成，1已完成，2已下单，3已收货
                    //查询红包状态
                    Integer copyStatus = iAppUserRedRewardService.selectStatusByIdAndType(userId, 1);
                    Integer buyStatus = iAppUserRedRewardService.selectStatusByIdAndType(userId, 3);

                    if (copyStatus == null || buyStatus == null) {
                        //隐藏免单
                        for (SyModuleChildrenVo syModuleChildrenVo : kingKongChildrenList) {
                            if ("3".equals(syModuleChildrenVo.getJumpType())) {
                                kingKongChildrenList.remove(syModuleChildrenVo);
                                break;
                            }
                        }
                        if (kkeSyModule != null && kingKongChildrenList != null && kingKongChildrenList.size() > 0) {
                            kkeSyModule.setModuleChildrenList(kingKongChildrenList);
                            map.put("moduleType", "a");//金刚眼返回a
                            map.put("kingKongEye", kkeSyModule);
                            return ServerResponse.createBySuccess("查询成功", map);
                        } else {
                            return ServerResponse.createBySuccess(201, "暂无数据", null);
                        }
                    }
                    if (copyStatus == 5) {
                        //复制链接完成
                        map.put("copyStatus", "1");
                    } else if (copyStatus == 1) {
                        map.put("copyStatus", "0");
                    } else {
                        map.put("copyStatus", "4");
                    }
                    if (buyStatus == 7) {
                        //已下单
                        map.put("buyStatus", "2");
                    } else if (buyStatus == 2) {
                        //已收货
                        map.put("buyStatus", "3");
                    } else if (buyStatus == 4) {
                        //红包失效
                        map.put("buyStatus", "4");
                    } else if (buyStatus == 1) {
                        //红包失效
                        map.put("buyStatus", "0");
                    } else {
                        //已领取
                        map.put("buyStatus", "1");
                    }
                    if (response.getStatus() == 516) {
                        //免单已完成
                        if (taskNum < 2) {
                            //登录，未完成任务显示红包列表
                            map.put("moduleType", "b");//显示红包列表
                            map.put("progressBar", String.valueOf(time));//进度条
                            map.put("loseTime", String.valueOf(loseTime));//倒计时
                            map.put("copyAward", appUserRewardSetup.getNewRedMoneyFixation().toString());
                            map.put("buyAward", appUserRewardSetup.getTaskRedMoneyAmount().toString());
                            map.put("inviteAward", appUserRewardSetup.getInvitationRedMoneyAmount().toString());
                            map.put("inviteStatus", "1");//已完成
                            return ServerResponse.createBySuccess("查询成功", map);
                        } else {
                            //隐藏免单
                            for (SyModuleChildrenVo syModuleChildrenVo : kingKongChildrenList) {
                                if ("3".equals(syModuleChildrenVo.getJumpType())) {
                                    kingKongChildrenList.remove(syModuleChildrenVo);
                                    break;
                                }
                            }
                            if (kkeSyModule != null && kingKongChildrenList != null && kingKongChildrenList.size() > 0) {
                                kkeSyModule.setModuleChildrenList(kingKongChildrenList);
                                map.put("moduleType", "a");//金刚眼返回a
                                map.put("kingKongEye", kkeSyModule);
                                return ServerResponse.createBySuccess("查询成功", map);
                            } else {
                                return ServerResponse.createBySuccess(201, "暂无数据", null);
                            }
                        }
                    }
                    //登录，未完成任务显示红包列表
                    map.put("moduleType", "b");//显示红包列表
                    map.put("loseTime", String.valueOf(loseTime));//倒计时
                    map.put("progressBar", String.valueOf(time));//进度条
                    map.put("copyAward", appUserRewardSetup.getNewRedMoneyFixation().toString());
                    map.put("buyAward", appUserRewardSetup.getTaskRedMoneyAmount().toString());
                    map.put("inviteAward", appUserRewardSetup.getInvitationRedMoneyAmount().toString());
                    map.put("inviteStatus", "0");//0元购
                    return ServerResponse.createBySuccess("查询成功", map);
                }
            }
            return ServerResponse.createBySuccess(201, "暂无数据", null);
        } else {

            map.put("moduleType", "b");//显示红包列表
            map.put("loseTime", "0");//倒计时
            map.put("progressBar", String.valueOf(time));//进度条
            map.put("copyAward", appUserRewardSetup.getNewRedMoneyFixation().toString());
            map.put("buyAward", appUserRewardSetup.getTaskRedMoneyAmount().toString());
            map.put("inviteAward", appUserRewardSetup.getInvitationRedMoneyAmount().toString());//邀请金额
            map.put("copyStatus", "0");
            map.put("buyStatus", "0");
            map.put("inviteStatus", "0");//0元购状态
            return ServerResponse.createBySuccess("查询成功", map);
        }
    }

    /**
     * 浮窗
     *
     * @param userId
     * @return
     */
   /* @Override
    public ServerResponse moduleFloating(Long userId) {
        HashMap map = new HashMap();
        //显示浮窗
        String redisKeyStr = "app_suspension_popup";
        List<BannerPictureVo> bannerPopupList = null;
        if (redisTemplateService.hasKey(redisKeyStr)) {
            bannerPopupList = redisTemplateService.getTByListKey(redisKeyStr, BannerPictureVo.class);
        }
        if (bannerPopupList == null) {
            bannerPopupList = bannerPictureMapper.bannerModuleList(7, null);//首页浮窗7
            redisTemplateService.set(redisKeyStr, bannerPopupList, 60 * 5);
        }

        if (userId != null) {
            ServerResponse response = iGoodsFreeService.checkHaveBuy(userId, null);
            BannerPictureVo bannerVo = floatingWindow(bannerPopupList);
            //登录状态判断是否购买免单，已购买隐藏浮窗
            if (response.getStatus() == 516) {
                //已购买免单，显示其他活动浮窗
                if (bannerVo != null) {
                    map.put("floating", bannerVo);
                } else {
                    return ServerResponse.createBySuccess(201, "暂无数据", null);
                }
                return ServerResponse.createBySuccess("查询成功", map);
            } else {
                //未购买免单显示浮窗 7天之内显示，7天后隐藏浮窗(定义浮窗modulecode 为7)

                //1 根据userId查询用户
                AppUser appUser = iAppUserService.selectAppUserByUserId(userId, 1);
                if (appUser != null && appUser.getUserLoginTime() != null) {
                    //以首次登陆时间为依据，判断时间是否超过7天
                    Date loginDate = appUser.getUserLoginTime();
                    Date loginDate2 = DateUtils.updateDayByDate(loginDate, 7);
                    long time = loginDate2.getTime();
                    if (time >= System.currentTimeMillis()) {
                        //显示免单浮窗
                        for (BannerPictureVo banner : bannerPopupList
                        ) {
                            if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 3) {
                                //jumpType = 3 跳免单
                                map.put("floating", banner);
                                return ServerResponse.createBySuccess("查询成功", map);
                            }
                        }
                        //显示其他活动浮窗
                        if (bannerVo != null) {
                            map.put("floating", bannerVo);
                            return ServerResponse.createBySuccess("查询成功", map);
                        } else {
                            return ServerResponse.createBySuccess(201, "暂无数据", null);
                        }

                    } else {
                        //显示其他活动浮窗
                        if (bannerVo != null) {
                            map.put("floating", bannerVo);
                        } else {
                            return ServerResponse.createBySuccess(201, "暂无数据", null);
                        }
                        return ServerResponse.createBySuccess("查询成功", map);
                    }
                } else {
                    //没有登陆时间，视为老用户，显示其他活动浮窗
                    //已购买免单，显示其他活动浮窗
                    if (bannerVo != null) {
                        map.put("floating", bannerVo);
                    } else {
                        return ServerResponse.createBySuccess(201, "暂无数据", null);
                    }
                    return ServerResponse.createBySuccess("查询成功", map);
                }
            }
        } else {
            //用户为空
            //显示免单浮窗
            for (BannerPictureVo banner : bannerPopupList
            ) {
                if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 3) {
                    //jumpType = 3 跳免单
                    map.put("floating", banner);
                    return ServerResponse.createBySuccess("查询成功", map);
                }
            }

        }
        return ServerResponse.createBySuccess(201, "暂无数据", null);
    }*/

    /**
     * 浮窗
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse moduleFloating(Long userId) {
        HashMap map = new HashMap();
        //显示浮窗
        String redisKeyStr = "app_suspension_popup";
        List<BannerPictureVo> bannerPopupList = null;
        if (redisTemplateService.hasKey(redisKeyStr)) {
            bannerPopupList = redisTemplateService.getTByListKey(redisKeyStr, BannerPictureVo.class);
        }
        if (bannerPopupList == null) {
            bannerPopupList = bannerPictureMapper.bannerModuleList(7, null);//首页浮窗7
            redisTemplateService.set(redisKeyStr, bannerPopupList, 60 * 5);
        }

        if (userId != null) {

            //1 根据userId查询用户
            AppUser appUser = iAppUserService.selectAppUserByUserId(userId, 1);
            if (appUser != null && appUser.getUserLoginTime() != null) {
                //以首次登陆时间为依据，判断时间是否超过7天
                Date loginDate = appUser.getUserLoginTime();
                Date loginDate2 = DateUtils.updateDayByDate(loginDate, 7);
                long time = loginDate2.getTime();
                if (time >= System.currentTimeMillis()) {
                    //显示浮窗
                    for (BannerPictureVo banner : bannerPopupList
                    ) {
                        if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 11) {
                            //jumpType = 11 跳社群活动链接
                            map.put("floating", banner);
                            return ServerResponse.createBySuccess("查询成功", map);
                        }
                    }

                } else {

                    return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                }
            } else {
                //没有登陆时间，视为老用户
                return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
            }
        }
        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
    }

    /**
     * 模块所有开关
     *
     * @return
     */
    @Override
    public ServerResponse moduleOnOffList() {
        String redisKeyStr = "app_switch_all";
        List<SyModuleOnOffVo> list = null;

        if (redisTemplateService.hasKey(redisKeyStr)) {
            list = redisTemplateService.getTByListKey(redisKeyStr, SyModuleOnOffVo.class);
        }
        if (list == null || list.size() <= 0) {
            list = syModuleMapper.syModuleOnOffList();
            for (SyModuleOnOffVo syModuleOnOff : list
            ) {
                //广告弹窗返回true
                if (syModuleOnOff.getTableId() == 6) {
                    syModuleOnOff.setOnOff(true);
                    break;
                }
            }
            redisTemplateService.set(redisKeyStr, list, 60 * 5);
        }
        return ServerResponse.createBySuccess("查询成功", list);
    }

    /**
     * 免单banner
     *
     * @param companyId
     * @param user
     * @return
     */
    @Override
    public ServerResponse bannerFreeList(Integer companyId, AppUser user) {

        if (user != null && user.getUserId() != null) {
            //以首次登陆时间为依据，判断时间是否超过7天
            //1 根据userId查询用户
            AppUser appUser = iAppUserService.selectAppUserByUserId(user.getUserId(), 1);
            if (appUser != null && appUser.getUserLoginTime() != null) {
                Date loginDate = appUser.getUserLoginTime();
                Date loginDate2 = DateUtils.updateDayByDate(loginDate, 7);
                long time = loginDate2.getTime();
                if (time >= System.currentTimeMillis()) {
                    return ServerResponse.createByErrorCodeMessage(201, "暂无数据");
                }
            }
        }

        List<BannerPictureVo> bannerList = null;
        Map map = new HashMap();
        String redisKey = "app_index_module_freeList";
        String activityIdKey = "sy_banner_free_activityId";
        if (redisTemplateService.hasKey(redisKey)) {
            bannerList = redisTemplateService.getTByListKey(redisKey, BannerPictureVo.class);
        }
        if (bannerList == null) {
            bannerList = bannerPictureMapper.bannerModuleList(2, null);
            redisTemplateService.set(redisKey, bannerList, 60 * 5);
        }
        if (bannerList == null || bannerList.size() <= 0) {
            return ServerResponse.createByErrorCodeMessage(201, "暂无数据");
        } else {
            String key = "sy_banner_free_height";
            if (redisTemplate.hasKey(key)) {
                map.put("high", redisTemplate.opsForValue().get(key));
            } else {
                map.put("high", "35");
            }
            if (user == null || user.getUserId() == null || !redisTemplateService.hasKey(activityIdKey)) {
                map.put("bannerList", bannerList);
            } else {
                AppUser appUser = iAppUserService.selectAppUserByUserId(user.getUserId(), 0);
                if (appUser.getTaobaoUserId() == 0 || appUser.getUserTaobaoAuthorization() == 1) {
                    map.put("bannerList", bannerList);
                    return ServerResponse.createBySuccess("查询成功", map);
                }
                TaobaoScheme taobaoScheme = null;
                AppCompany com;

                String generalizePid = "";
                String appSession = "";

                //用户不为空，推广id不为空时，查询用户对应的推广位
                if (appUser != null && appUser.getSchemeId() != null && appUser.getSchemeId() != 0) {
                    taobaoScheme = iTaobaoSchemeService.selectTaobaoSchemeById(appUser.getSchemeId(), 0);
                    if (taobaoScheme != null && taobaoScheme.getGeneralizePid() != null && taobaoScheme.getAppSession() != null) {
                        generalizePid = taobaoScheme.getGeneralizePid();
                        appSession = taobaoScheme.getAppSession();
                    }
                }
                //generalizePid或者appSession 为空时，取公司的值
                boolean isNotHasScheam = (StringUtils.isEmpty(generalizePid) || StringUtils.isEmpty(appSession));

                if (isNotHasScheam) {
                    com = appCompanyService.findtAppCompany(appUser == null ? null : appUser.getCompanyId(), 1);
                    generalizePid = com.getGeneralizePid();
                    appSession = com.getTaoBaoScheme().getAppSession();
                }
                Long siteId = Long.valueOf(generalizePid.split("_")[2]);
                Long adzoneid = Long.valueOf(generalizePid.split("_")[3]);
                Long promotion_sceneid = Long.valueOf(redisTemplateService.getTByKey(activityIdKey, String.class));
                TbkScActivitylinkToolgetResponse response = sessionController.tbkScActivitylinkToolgetResponse(siteId, adzoneid, appSession, appUser.getRelationId().toString(), promotion_sceneid);
                if (response != null && response.getData() != null) {
                    bannerList.get(0).setPictureLink(response.getData());
                }
                map.put("bannerList", bannerList);
            }

            return ServerResponse.createBySuccess("查询成功", map);
        }

    }

    /**
     * banner 广告位
     *
     * @param companyId
     * @return
     */
    @Override
    public ServerResponse bannerAdvertisingList(Integer companyId) {
        List<BannerPictureVo> bannerList = null;
        String redisKey = "app_index_module_bannerAdvertisingList_" + companyId;
        if (redisTemplateService.hasKey(redisKey)) {
            bannerList = redisTemplateService.getTByListKey(redisKey, BannerPictureVo.class);
        }
        if (bannerList == null) {
            bannerList = bannerPictureMapper.bannerModuleList(1, companyId);
            redisTemplateService.set(redisKey, bannerList, 60 * 5);
        }
        if (bannerList == null || bannerList.size() <= 0) {
            return ServerResponse.createByErrorCodeMessage(201, "暂无数据");
        } else {
            return ServerResponse.createBySuccess("查询成功", bannerList);
        }
    }

    /**
     * banner淘宝活动
     *
     * @param companyId
     * @return
     */
    @Override
    public ServerResponse bannerTaoBaoActivityList(Integer companyId) {
        List<BannerPictureVo> bannerList = null;
        String redisKey = "app_index_module_taoBaoActivityList";
        if (redisTemplateService.hasKey(redisKey)) {
            bannerList = redisTemplateService.getTByListKey(redisKey, BannerPictureVo.class);
        }
        if (bannerList == null) {
            bannerList = bannerPictureMapper.bannerModuleList(3, null);
            redisTemplateService.set(redisKey, bannerList, 60 * 5);
        }
        if (bannerList == null || bannerList.size() <= 0) {
            return ServerResponse.createByErrorCodeMessage(201, "暂无数据");
        } else {
            return ServerResponse.createBySuccess("查询成功", bannerList);
        }
    }

    /**
     * 秒杀小喇叭
     *
     * @return
     */
    @Override
    public ServerResponse moduleTrumpet() {
        List<BannerPictureVo> bannerList = null;
        String redisKey = "app_index_module_trumpet";
        if (redisTemplateService.hasKey(redisKey)) {
            bannerList = redisTemplateService.getTByListKey(redisKey, BannerPictureVo.class);
        }
        if (bannerList == null) {
            bannerList = bannerPictureMapper.bannerModuleList(8, null);
            redisTemplateService.set(redisKey, bannerList, 60 * 5);
        }
        if (bannerList == null || bannerList.size() <= 0) {
            return ServerResponse.createByErrorCodeMessage(201, "暂无数据");
        } else {
            java.util.Calendar cale = java.util.Calendar.getInstance();
            int hour = cale.get(Calendar.HOUR_OF_DAY);
            if (hour > 10 && bannerList.size() == 2) {
                return ServerResponse.createBySuccess("查询成功", bannerList.get(1));
            }
            return ServerResponse.createBySuccess("查询成功", bannerList.get(0));
        }
    }

    @Override
    public ServerResponse KingBgImage() {
        Map<Object, Object> bannerMap = new HashMap<>();
        String redisKey = "app_index_module_king_bgImage";
        if (redisTemplateService.hasKey(redisKey)) {
            bannerMap = redisTemplateService.getMap(redisKey, Map.class);
        }
        if (bannerMap.size() <= 0) {
            List<BannerPictureVo> bannerPictureVos = bannerPictureMapper.bannerModuleList(9, null);
            List<BannerPictureVo> bannerPictureVos1 = bannerPictureMapper.bannerModuleList(10, null);
            if (bannerPictureVos != null && bannerPictureVos.size() > 0) {
                bannerMap.put("kingBgImageBig", bannerPictureVos.get(0).getMainPictureUrl());
            } else {
                bannerMap.put("kingBgImageBig", "http://qiniuimage.shengyaapp.com/FvzrMmntRJnINmYs7y0WN5WzbcSD");
            }
            if (bannerPictureVos1 != null && bannerPictureVos1.size() > 0) {
                bannerMap.put("kingBgImageSmall", bannerPictureVos1.get(0).getMainPictureUrl());
            }
            redisTemplateService.setMap(redisKey, bannerMap, 0l);
            redisTemplateService.expire(redisKey, 60);
        }
        if (bannerMap == null || bannerMap.size() <= 0) {
            return ServerResponse.createByErrorCodeMessage(201, "暂无数据");
        } else {
            return ServerResponse.createBySuccess("查询成功", bannerMap);
        }
    }

    /**
     * 广告浮窗判断
     *
     * @param bannerPopupList
     * @return
     */
    public BannerPictureVo floatingWindow(List<BannerPictureVo> bannerPopupList) {
        for (BannerPictureVo banner : bannerPopupList) {
            if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 1) {//今日爆款
                return banner;
            } else if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 2) {//白菜专区
                return banner;
            } else if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 5) {//邀请抓钱
                return banner;
            } else if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 6) {//签到
                return banner;
            } else if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 11) {//h5页面
                return banner;
            } else if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 12) {//跳商品详情
                return banner;
            } else if (banner != null && banner.getJumpType() != null && banner.getJumpType() == 13) {//省钱教程
                return banner;
            }
        }
        return null;
    }

    @Override
    public String getJingDongUrl(Long userId, String materialId, String couponUrl) {
        String url = "";
        JdClient client = new DefaultJdClient(JDConfig.JD_URL, null, JDConfig.JD_APPKEY, JDConfig.JD_APPSECRET);
        UnionOpenPromotionBysubunionidGetRequest request = new UnionOpenPromotionBysubunionidGetRequest();
        PromotionCodeReq promotionCodeReq = new PromotionCodeReq();
        if (userId == null) {
            promotionCodeReq.setSubUnionId("0");
        } else {
            promotionCodeReq.setSubUnionId(userId.toString());
        }
        if (!StringUtils.isEmpty(couponUrl)) {
            promotionCodeReq.setCouponUrl(couponUrl);
        }
        promotionCodeReq.setMaterialId(materialId);
        request.setPromotionCodeReq(promotionCodeReq);
        UnionOpenPromotionBysubunionidGetResponse response = null;
        try {
            response = client.execute(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (response.getCode() == 200) {
            url = response.getData().getShortURL();
        }
        return url;
    }

    private String getMeiTuanUrl(Long userId) {
        StringBuilder url = new StringBuilder(MeiTuanConfig.MEITUAN_URL);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String utmMedium = MeiTuanAEC.encryptHex(userId.toString(), MeiTuanConfig.PASS_KEY);
        StringBuilder requestId = new StringBuilder(MeiTuanConfig.UTM_SOURCE_ID).append(timestamp);
        String access_token = MeiTuanAEC.encryptHex(requestId.toString(), MeiTuanConfig.PASS_KEY);
        url = url.append("?utmSource=").append(MeiTuanConfig.UTM_SOURCE_ID)//渠道ID
                .append("&utmMedium=").append(utmMedium)//子媒体ID,加密
                .append("&access_token=").append(access_token)//加密
                .append("&timestamp=").append(timestamp)//时间戳
                .append("&requestId=").append(requestId.toString())//拼接生成
                .append("&activity=").append(MeiTuanConfig.ACTIVITY_ID)//活动ID
                .append("&version=").append(MeiTuanConfig.VERSEION);//版本
        return url.toString();
    }

    /**
     * 拼多多转链
     *
     * @param userId
     * @return
     */
    private String getPinDuoDuoUrl(Long userId) {
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("client_id", PDDConfig.PDD_CLIENT_ID);
        treeMap.put("custom_parameters", userId.toString());
        treeMap.put("data_type", PDDConfig.PDD_DATA_TYPE);
        treeMap.put("pid", PDDConfig.PDD_PID);
        treeMap.put("timestamp", timestamp);
        treeMap.put("type", PDDConfig.PDD_URL_TYPE);
        String sign = SignMD5Util.getPDDSignStr(treeMap, PDDConfig.PDD_CLIENT_SECRET);
        //拼接链接
        StringBuilder url = new StringBuilder(PDDConfig.PDD_HOME_URL);
        url = url.append("?type=").append(PDDConfig.PDD_URL_TYPE)
                .append("&data_type=").append(PDDConfig.PDD_DATA_TYPE)
                .append("&timestamp=").append(timestamp)//秒级时间戳
                .append("&client_id=").append(PDDConfig.PDD_CLIENT_ID)
                .append("&custom_parameters=").append(userId.toString())
                .append("&pid=").append(PDDConfig.PDD_PID)
                .append("&sign=").append(sign);

        String pddResponse = HttpUtils.sendGet(url.toString(), "");
        PDDUrlResponse.SingleUrlList singleUrlList = null;
        JSONObject object = JSONObject.parseObject(pddResponse);
        String resource_url = object.getString("resource_url_response");
        PDDUrlResponse response = JSONObject.parseObject(resource_url, PDDUrlResponse.class);
        singleUrlList = response.getSingle_url_list();


        return singleUrlList.getUrl();
    }

    private String getElmUrl(Long userId) {
        AppUser appUser = iAppUserService.selectAppUserByUserId(userId, 1);
        TaobaoScheme taobaoScheme = null;
        AppCompany com;
        String elmkey = "sy_module_elm_activityId";
        String generalizePid = "";
        String appSession = "";
        String elmUrl = "";
        //用户不为空，推广id不为空时，查询用户对应的推广位
        if (appUser != null && appUser.getSchemeId() != null && appUser.getSchemeId() != 0) {
            taobaoScheme = iTaobaoSchemeService.selectTaobaoSchemeById(appUser.getSchemeId(), 0);
            if (taobaoScheme != null && taobaoScheme.getGeneralizePid() != null && taobaoScheme.getAppSession() != null) {
                generalizePid = taobaoScheme.getGeneralizePid();
                appSession = taobaoScheme.getAppSession();
            }
        }
        //generalizePid或者appSession 为空时，取公司的值
        boolean isNotHasScheam = (StringUtils.isEmpty(generalizePid) || StringUtils.isEmpty(appSession));

        if (isNotHasScheam) {
            com = appCompanyService.findtAppCompany(appUser == null ? null : appUser.getCompanyId(), 1);
            generalizePid = com.getGeneralizePid();
            appSession = com.getTaoBaoScheme().getAppSession();
        }
        Long siteId = Long.valueOf(generalizePid.split("_")[2]);
        Long adzoneid = Long.valueOf(generalizePid.split("_")[3]);
        Long promotion_sceneid = Long.valueOf(redisTemplateService.getTByKey(elmkey, String.class));
        TbkScActivitylinkToolgetResponse response = sessionController.tbkScActivitylinkToolgetResponse(siteId, adzoneid, appSession, appUser.getRelationId().toString(), promotion_sceneid);
        if (response != null && response.getData() != null) {
           elmUrl = response.getData();
        }
        return elmUrl;
    }
    public static void main(String[] args) {


        StringBuilder url = new StringBuilder(MeiTuanConfig.MEITUAN_URL);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String utmMedium = MeiTuanAEC.encryptHex("18839357210", MeiTuanConfig.PASS_KEY);
        StringBuilder requestId = new StringBuilder(MeiTuanConfig.UTM_SOURCE_ID).append(timestamp);
        String access_token = MeiTuanAEC.encryptHex(requestId.toString(), MeiTuanConfig.PASS_KEY);
        url = url.append("?utmSource=").append(MeiTuanConfig.UTM_SOURCE_ID)//渠道ID
                .append("&utmMedium=").append(utmMedium)//子媒体ID,加密
                .append("&access_token=").append(access_token)//加密
                .append("&timestamp=").append(timestamp)//时间戳
                .append("&requestId=").append(requestId.toString())//拼接生成
                .append("&activity=").append(MeiTuanConfig.ACTIVITY_ID)//活动ID
                .append("&version=").append(MeiTuanConfig.VERSEION);//版本
        System.out.println(url);
    }
}
